import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import 'package:situation/app/theme/gaps.dart';

class DistanceMeasureTool extends StatefulWidget {
  final Color lineColor;
  final double lineWidth;
  final TextStyle distanceStyle;

  final Function? onClose;
  const DistanceMeasureTool({
    super.key,
    this.lineColor = Colors.blue,
    this.lineWidth = 3.0,
    this.distanceStyle = const TextStyle(
      color: Colors.black,
      backgroundColor: Colors.white,
      fontSize: 12,
    ), this.onClose,
  });

  static late final GlobalKey<_DistanceMeasureToolState> stateKey =
  GlobalKey<_DistanceMeasureToolState>();

  static void addPoint(LatLng point) => stateKey.currentState?._addPoint(point);

  @override
  State<DistanceMeasureTool> createState() => _DistanceMeasureToolState();
}

class _DistanceMeasureToolState extends State<DistanceMeasureTool> {
  final List<LatLng> _points = [];
  final List<double> _distances = [];
  final Distance _distanceCalculator = const Distance();

  void _addPoint(LatLng point) {
    setState(() {
      _points.add(point);
      if (_points.length > 1) {
        // 计算与前一个点的距离（米）
        final double dist = _distanceCalculator(
          _points[0],
          _points.last,
        );
        _distances.add(dist);
      }
    });
  }

  void _undoPoint() {
    if (_points.isEmpty) return;
    setState(() {
      _points.removeLast();
      if (_distances.isNotEmpty) {
        _distances.removeLast();
      }
    });
  }

  void _clearAll() {
    setState(() {
      _points.clear();
      _distances.clear();
    });
    if( widget.onClose!=null){
      widget.onClose!();
    }

  }

  Widget _buildDistanceLabels() {
    return MarkerLayer(
      markers: [
        for (int i = 0; i < _distances.length; i++)
          Marker(
            width: 100,
            height: 50,
            point: _points[i + 1],
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 4),
                  decoration: BoxDecoration(
                    color: widget.distanceStyle.backgroundColor,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    _formatDistance(_distances[i]), // 修改这里
                    style: widget.distanceStyle,
                  ),
                ),
              ],
            ),
          ),
      ],
    );
  }


// 新增格式化方法
  String _formatDistance(double meters) {
    if (meters >= 1000) {
      return '${(meters / 1000).toStringAsFixed(2)}km';
    }
    return '${meters.toStringAsFixed(2)}m';
  }

  Widget _buildIconButton({
    required IconData icon,
    required Color color,
    required VoidCallback onPressed
  }) {
    return GestureDetector(
      onTap: onPressed,
      child: Container(
        padding: EdgeInsets.all(6),
        decoration: BoxDecoration(
          color: Colors.white,
          shape: BoxShape.circle,
        ),
        child: Icon(icon, size: 20, color: color),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 绘制连接线
        PolylineLayer(
          polylines: [
            if (_points.length >= 2)
              Polyline(
                points: _points,
                color: widget.lineColor,
                strokeWidth: widget.lineWidth,
              ),
          ],
        ),

        // 绘制测量点
        MarkerLayer(
          markers: [
            for (final point in _points)
              Marker(
                width: 20,
                height: 20,
                point: point,
                child: GestureDetector(
                  onLongPress: () => _undoPoint(),
                    child: Icon(Icons.circle, size: 20,color: Colors.blue,),
                ),
              ),
          ],
        ),

        // 显示距离标签
        _buildDistanceLabels(),

        // 控制面板
        Positioned(
          right: 20,
          bottom: Get.height*0.4,
          child: Container(
            padding: _points.isEmpty ? const EdgeInsets.all(0) :const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.black.withAlpha(80),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Column(
              children: [
                if(_points.isNotEmpty) ...[
                  _buildIconButton(
                    icon: Icons.undo,
                    color: Colors.orange,
                    onPressed: _undoPoint,
                  ),
                  Gaps.vGap8,
                  _buildIconButton(
                    icon: Icons.clear,
                    color: Colors.red,
                    onPressed: _clearAll,
                  )
                ]
              ],
            ),
          ),
        ),
      ],
    );
  }
}

